package com.jason.data.agentbase.agent.jdkAgent;

import com.jason.data.agentbase.agent.A;
import com.jason.data.agentbase.agent.Aimpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk动态代理，利用反射机制，基于接口创建被代理对象的代理实例（仅支持基于接口（不是方法，是interface）进行代理，无法对类进行代理）代理类通过实现InvocationHander.invok();
 */
public class JdkProxyTest implements InvocationHandler {

    private A a;

    public JdkProxyTest(A a){
        this.a = a;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("jdk代理-invoke执行~~~~");
        return method.invoke(a,args);
    }

    public static A newProxyInstance(A a){
        return (A) Proxy.newProxyInstance(JdkProxyTest.class.getClassLoader(),new Class[]{A.class},new JdkProxyTest(a));
    }

    public static void main(String[] args) {
        A a = new Aimpl();
        A jdkProxy = JdkProxyTest.newProxyInstance(a);
        jdkProxy.a();
        jdkProxy.b();
    }
}
